package thread;

import io.vertx.core.json.JsonObject;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * thread.SocketThread
 *
 * @author liyixin
 * @date 2019/1/21
 */
public class SocketThread extends Thread{

    private int port;
    private String ip;

    public SocketThread(String ip,int port) {
        this.port = port;
        this.ip = ip;
    }

    @Override
    public void run() {
        try {
            ExecutorService SERVICE = new ThreadPoolExecutor(20, Integer.MAX_VALUE,
                    60L, TimeUnit.SECONDS,
                    new SynchronousQueue<Runnable>());

            ServerSocket serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress( ip,port));

            System.out.println("IO Server Start :" + ip + " : " + port);
            while (true) {
                Socket socket = serverSocket.accept();
                SERVICE.execute(() -> {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                        JsonObject msg = new JsonObject(br.readLine());
                        int size = Integer.parseInt(msg.getJsonObject("dataMap").getString("obj_size"));
                        bw.write("ok*");
                        bw.flush();

                        char[] sysBytes = new char[512];
                        br.read(sysBytes,0,512);

                        File file = new File("/fs-SP2-1/test/test");
                        BufferedWriter fw = new BufferedWriter(new FileWriter(file));

                        long startTime = System.currentTimeMillis();

                        fw.write(sysBytes);

                        int recvall = 0;
                        int recv;
                        while (recvall < size) {
                            recv = br.read(sysBytes,0,sysBytes.length);
                            recvall += recv;
                            fw.write(sysBytes,0,recv);
                        }

                        long endTime = System.currentTimeMillis();
                        //System.out.println("time :" + (endTime - startTime));

                        bw.write("B89117B0DD1FDC9863202A8E25FDFC83*");
                        bw.flush();
                        fw.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
